from typing import List

from kubernetes import client
from lucommon.logger import lu_logger

from k8s.base import KubernetesAPI


class RbacAPI(KubernetesAPI):

    def _make_api(self, api_client):
        self.Api = client.RbacAuthorizationV1Api(api_client)

    def get_cluster_role(self, role_name: str):
        try:
            roles = self.Api.list_cluster_role(**{
                "field_selector": "metadata.name={}".format(role_name)
            })

            items = roles.items
            return items[0] if items else None, ""
        except Exception as e:
            return None, str(e)

    def get_cluster_role_binding(self, role_binding_name: str):
        try:
            role_binding = self.Api.list_cluster_role_binding(**{
                "field_selector": "metadata.name={}".format(role_binding_name)
            })

            items = role_binding.items
            return items[0] if items else None, ""
        except Exception as e:
            return None, str(e)

    def create_cluster_role(self, role: str, rule_list: List[client.V1PolicyRule]):
        try:
            r = self.Api.create_cluster_role(
                body=client.V1ClusterRole(**{
                    "api_version": self.api_version,
                    "kind": "ClusterRole",
                    "metadata": client.V1ObjectMeta(**{
                        "name": role
                    }),
                    "rules": rule_list
                })
            )
            lu_logger.debug("clusterrole {} created".format(role))
            return r, None
        except Exception as e:
            lu_logger.debug("clusterrole {} created failed,{}".format(role, str(e)))
            return None, str(e)

    def create_cluster_role_binding(self, role: str, role_binding: str, subjects: List[client.V1Subject]):
        try:
            r = self.Api.create_cluster_role_binding(
                body=client.V1ClusterRoleBinding(**{
                    "api_version": self.api_version,
                    "kind": "ClusterRoleBinding",
                    "metadata": client.V1ObjectMeta(**{
                        "name": role_binding,
                    }),
                    "role_ref": client.V1RoleRef(**{
                        "api_group": self.api_group,
                        "kind": "ClusterRole",
                        "name": role,
                    }),
                    "subjects": subjects
                })
            )
            lu_logger.debug("clusterrolebinding {} created".format(role_binding))
            return r, None
        except Exception as e:
            lu_logger.debug("clusterrolebinding {} created failed,{}".format(role_binding, str(e)))
            return None, str(e)
